#include "TabWidget.h"
#include <qdebug.h>
#include "PlainEdit.h"


TabWidget::TabWidget(QWidget* parent)
{
    this->setTabsClosable(true);
    connect(this, SIGNAL(tabCloseRequested(int)), this, SLOT(closeTab(int)));
    this->setParent(parent);
}

TabWidget::~TabWidget()
{
    delete this->tb;
}

void TabWidget::closeTab(const int index)
{
    int count = this->count();

    if(index != 0 || count > 1) //close the first tab only if there is more than one tab
    {
        PlainEdit* ed = static_cast<PlainEdit*>(this->widget(index));

        if(!ed)
            return;

        if(!ed->saved)
        {
            int ret = QMessageBox::question(this, "LUA Editor", tr("Save file \"%1\"?").arg(ed->filepath), QMessageBox::Yes, QMessageBox::No, QMessageBox::Cancel);

            if(ret == QMessageBox::Yes)
            {
                if(!save(index))
                    return;
            }
            else if(ret == QMessageBox::Cancel)
                return;
        }

        this->removeTab(index);
        delete ed;
    }
    else //never close the last tab just clean it up
    {
        PlainEdit* ed = static_cast<PlainEdit*>(this->widget(index));

        if(!ed)
            return;

        if(!ed->saved)
        {
            int ret = QMessageBox::question(this, "LUA Editor", tr("Save file \"%1\"?").arg(ed->filepath), QMessageBox::Yes, QMessageBox::No, QMessageBox::Cancel);

            if(ret == QMessageBox::Yes)
            {
                if(!save(index))
                    return;
            }
            else if(ret == QMessageBox::Cancel)
                return;
        }

        this->setTabText(0, "untitled.lua");
        ed->setPlainText("");
        ed->filepath.clear();
        ed->saved = true; //same here -> you dont need to save empty files
    }
}

bool TabWidget::save(const int wIndex)
{
    PlainEdit* ed = static_cast<PlainEdit*>(this->widget(wIndex));

    if(!ed)
        return false;

    if(ed->filepath.isEmpty())
        ed->filepath = QFileDialog::getSaveFileName (0, tr("Speichern unter..."), QString(), "*.lua"   );

    if(ed->filepath.isEmpty())
        return false;

    QFile file(ed->filepath);
    if(!file.open(QFile::WriteOnly | QFile::Text))
            return false;

    QTextStream out(&file);
    QApplication::setOverrideCursor(Qt::WaitCursor);
    out << ed->toPlainText();
    QApplication::restoreOverrideCursor();

    QString shownName;
    if(ed->filepath.isEmpty())
        shownName = tr("untiteld.lua");
    else
        shownName = tr("%1").arg(QFileInfo(ed->filepath).fileName());

    this->setTabText(wIndex, shownName);
    return true;
}
